package com.gqr.threadobjectclasscommonmethods;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:WaitNotifyAll
 * author:guqingrong
 * Date:2024-04-21 22:11
 * Description: 3个线程 线程1 和线程2首先被阻塞 线程3 唤醒他们 notify notifyAll
 * start先执行不代表线程先启动
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class WaitNotifyAll implements Runnable {
    private static final Object resourceA = new Object();

    public static void main(String[] args) throws InterruptedException {
        WaitNotifyAll r = new WaitNotifyAll();
        Thread threadA = new Thread(r);
        Thread threadB = new Thread(r);

        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resourceA) {
                    resourceA.notifyAll();
                    System.out.println("线程C通知全部了");
//                    resourceA.notify();
//                    System.out.println("线程C通知某一个");
                }
            }
        });

        threadA.start();
        threadB.start();
        // 不休眠 线程启动顺序无法保证
        Thread.sleep(200);
        threadC.start();
    }
    @Override
    public void run() {
        synchronized (resourceA){
            System.out.println("线程"+Thread.currentThread().getName()+"获取资源A的锁");
            try {
                System.out.println("线程"+Thread.currentThread().getName()+"等待下一步的开始");

                resourceA.wait();
                System.out.println("线程"+Thread.currentThread().getName()+"马上就结束了");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
